
clear all
set more off

/* Inputs */ 
 
*cd /data2/cedsei/firm 

********************************************************************************
local fek = 0
if `fek'== 1 {
foreach num of numlist 2005(1)2018 {
	di "Year `num'"
	qui {
	clear
	use lopnr_peorgnr juridiskform imputeradeforetag nettoomsattning bransch_sni* ///
	verkstalldutdelning kassaochbank summatillgangar  summakostnaderforravarorochhande ///
	if juridiskform=="49" using ///
	"/data/rawdata/cleaned/fek_`num'",clear
	if `num'<2010 {
		keep if imputeradeforetag=="0" 
	}
	else {
		keep if imputeradeforetag==0		
	}
	drop imputeradeforetag juridiskform
	rename nettoomsattning sales_fek
	rename verkstalldutdelning div_fek
	rename kassaochbank   bs_cashandbank_fek
	rename summatillgangar bs_assetstot_fek
	rename summakostnaderforravarorochhande inc_costsrawmatsandresale
	gen flag_fek = sales_fek<0
	replace sales_fek=0 if sales_fek<0
	gen year = `num'
	winsor2 sales_fek, cuts(0 99.5) suffix(_w05) by(year)
	winsor2 sales_fek, cuts(0 99) suffix(_w1) by(year)
	winsor2 sales_fek, cuts(0 95) suffix(_w5) by(year)
	winsor2 sales_fek, cuts(0 90) suffix(_w10) by(year)

	if `num'>2005 {
		append using firm_temp
	}
	save firm_temp, replace
	}
}
}

local serrano = 1
if `serrano'== 1 {
	clear 
	use "/data/rawdata/SCB/SCB_Leverans_20221117/DS_Lev_Serrano_Serrano"
	rename peorglopnr lopnr_peorgnr 
	rename ser_year year 
	keep if ser_jurform==49
	drop if mi(lopnr_peorgnr)
	keep if inrange(year,2005,2018)
	drop if mi(rr01_ntoms)
	keep if mi(bslov_imput)
	keep if bslov_antmonth ==12 
	tostring bslov_bslslut_min, replace
	gen length_min = length(bslov_bslslut_min)
	gen acc_min = substr(bslov_bslslut_min,3,4) if length_min==6
	replace acc_min = substr(bslov_bslslut_min,2,4) if length_min==5
	order lopnr_peorgnr year acc_min
	// keep if acc_min =="1231"
	keep lopnr_peorgnr year rr01_ntoms bslov_antanst rr00_utdbel ///
	br07_kplackaba br07b_kabasu br09_tillgsu 
	rename rr00_utdbel div_ser
	rename br07b_kabasu bs_cashandbank_ser 
	rename br07_kplackaba bs_liquid_ser 
	rename rr01_ntoms sales_ser
	rename br09_tillgsu bs_assetstot_ser
	replace sales_ser = sales_ser*1000
	keep lopnr_peorgnr year sales_ser bslov_antanst div_ser ///
	bs_cashandbank_ser bs_liquid_ser bs_assetstot_ser
	gen flag_ser = sales_ser<0
	replace sales_ser=0 if sales_ser<0
	winsor2 sales_ser, cuts(0 99.5) suffix(_w05) by(year)
	winsor2 sales_ser, cuts(0 99) suffix(_w1) by(year)
	winsor2 sales_ser, cuts(0 95) suffix(_w5) by(year)
	winsor2 sales_ser, cuts(0 90) suffix(_w10) by(year)
	
	save firm_temp_ser, replace 
}
